package diet

import (
	"encoding/json"
	"fmt"
	"github.com/bgmp/config"
	"github.com/bgmp/handler"
	"github.com/bgmp/middleware"
	"github.com/bgmp/model"
	"github.com/gin-gonic/gin"
	"github.com/mohae/deepcopy"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"io"
	"net/http"
)

type Result struct {
	Food   int      `json:"food"`
	Region string   `json:"region"`
	Top5   []string `json:"top5"`
}

type SegBackResponse struct {
	MaskSid model.Sid `json:"maskSid"`
	Results []Result  `json:"results"`
}

type SegRecResponse struct {
	DietId  uint     `json:"dietId"`
	Results []Result `json:"results"`
}

type SegRecRequest struct {
	Sid model.Sid `json:"sid"`
	Num int       `json:"num"`
}

var tmpResult = SegRecResponse{
	DietId: 736,
	Results: []Result{
		{
			Food:   38,
			Region: "6pbosvxmpx",
			Top5:   []string{"海参", "紫菜包饭", "玉米棒", "青椒", "皮蛋"},
		}, {
			Food:   135,
			Region: "6pbosw2a85",
			Top5: []string{"荞麦馒头",
				"馒头",
				"芝麻糊",
				"菜包",
				"南瓜紫薯馒头"},
		}, {
			Food:   203,
			Region: "6pbosw7whx",
			Top5: []string{"鸡蛋",
				"牛奶",
				"双皮奶",
				"豆浆",
				"汤圆"},
		},
	}}

func saveAndReturn(userId uint, sid model.Sid) *SegRecResponse {
	food := model.Food{
		Name: "海参",
		Nutrition: []struct {
			Key   string `json:"key"`
			Value string `json:"value"`
		}{
			{Key: "质量", Value: "20.813g"},
			{Key: "碳水化合物", Value: "0.520g"},
			{Key: "蛋白质", Value: "3.434g"},
			{Key: "脂肪", Value: "0.042g"},
		},
	}
	foods := model.Foods{
		MaskSid:  int64(sid),
		FoodList: []model.Food{food},
	}
	diet := model.Diet{
		DietMeta: model.DietMeta{
			UserId: userId,
		},
		DietField: model.DietField{
			PicId: sid,
			Foods: foods,
		},
	}
	err := diet.Create(config.DB)
	if err == nil {
		tmpResult.DietId = diet.ID
		tmp := deepcopy.Copy(tmpResult).(SegRecResponse)
		tmp.DietId = diet.ID
		return &tmp
	}
	return &tmpResult
}

func (b Base) SegRec(c *gin.Context, req *SegRecRequest) *SegRecResponse {
	num := req.Num
	sid := req.Sid
	userId := middleware.GetUserId(c)

	// 请求 python
	url := fmt.Sprintf(viper.GetString("segback"), sid.String(), num)
	log.Info(url)
	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		handler.Errorf(c, err.Error())
		return nil
	}
	client := &http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		//handler.Errorf(c, err.Error())
		return saveAndReturn(userId, sid)
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		//handler.Errorf(c, "failed to seg rec")
		log.Error("resp error is ", resp)
		return saveAndReturn(userId, sid)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		//handler.Errorf(c, err.Error())
		return saveAndReturn(userId, sid)
	}
	rsp := SegBackResponse{}
	err = json.Unmarshal(body, &rsp)
	if err != nil {
		//handler.Errorf(c, err.Error())
		return saveAndReturn(userId, sid)
	}

	foods := model.Foods{
		MaskSid:  int64(rsp.MaskSid),
		FoodList: nil,
	}
	//bytes, _ := json.Marshal(foods)
	diet := model.Diet{
		DietMeta: model.DietMeta{
			UserId: middleware.GetUserId(c),
		},
		DietField: model.DietField{
			PicId: sid,
			Foods: foods,
		},
	}
	err = diet.Create(config.DB)
	if err != nil {
		log.Error(err)
		//handler.Errorf(c, "failed to create diet")
		return saveAndReturn(userId, sid)
	}

	if len(rsp.Results) <= 0 {
		return saveAndReturn(userId, sid)
	}

	return &SegRecResponse{
		DietId:  diet.ID,
		Results: rsp.Results,
	}
}
